import os
import logging
from typing import Dict, Any, List

from django.http import FileResponse, HttpResponse
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser

from services.file_service import FileService
from services.database_service import DatabaseService
from .utils import api_error_handler

logger = logging.getLogger('api')
file_service = FileService()
db_service = DatabaseService()

@api_view(['POST'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
@api_error_handler
def upload_file(request):
    """
    上传文件API
    
    请求参数:
    - file: 要上传的文件
    - type: 文件类型 (video, audio, image, etc.)
    - project_id: (可选) 关联的项目ID
    - public: (可选) 是否公开访问，默认false
    - metadata: (可选) 文件元数据，JSON字符串
    
    返回:
    - 上传结果和资源信息
    """
    if 'file' not in request.FILES:
        return Response({
            'success': False,
            'message': '没有提供文件'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    file_obj = request.FILES['file']
    file_type = request.data.get('type', 'unknown')
    project_id = request.data.get('project_id')
    
    # 解析是否公开
    public = request.data.get('public', 'false').lower() == 'true'
    
    # 解析元数据
    metadata = {}
    try:
        if 'metadata' in request.data:
            import json
            metadata = json.loads(request.data['metadata'])
    except Exception as e:
        logger.warning(f"⚠️ 元数据解析失败: {str(e)}")
    
    # 添加用户信息到元数据
    metadata['uploaded_by'] = str(request.user.id)
    metadata['uploaded_by_username'] = request.user.username
    
    # 上传文件
    try:
        upload_result = file_service.upload_file(
            file_obj=file_obj,
            original_name=file_obj.name,
            file_type=file_type,
            project_id=project_id,
            metadata=metadata,
            public=public
        )
        
        # 创建资源记录
        # asset = file_service.create_asset_from_upload(upload_result, request.user.id)
        
        logger.info(f"✅ 文件上传成功: {upload_result['object_key']}")
        
        return Response({
            'success': True,
            'message': '文件上传成功',
            'data': {
                'file_url': upload_result['file_url'],
                'object_key': upload_result['object_key'],
                'original_name': upload_result['original_name'],
                'file_type': upload_result['file_type'],
                'is_public': upload_result['is_public'],
                'content_type': upload_result['content_type'],
                # 'asset_id': asset.id if asset else None
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 文件上传失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'文件上传失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
@api_error_handler
def delete_file(request, object_key=None):
    """
    删除文件API
    
    URL参数:
    - object_key: 文件的对象键
    
    返回:
    - 删除结果
    """
    if not object_key:
        return Response({
            'success': False,
            'message': '未提供文件标识'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 检查权限（这里应添加更多权限检查逻辑）
    if not (request.user.is_admin or request.user.is_superuser):
        # 检查文件是否属于该用户
        pass
    
    success = file_service.delete_file(object_key)
    
    if success:
        # 删除资源记录
        # db_service.delete_asset_by_path(object_key)
        
        logger.info(f"✅ 文件删除成功: {object_key}")
        return Response({
            'success': True,
            'message': '文件删除成功'
        })
    else:
        return Response({
            'success': False,
            'message': '文件删除失败'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
@api_error_handler
def get_file_url(request):
    """
    获取文件URL API
    
    查询参数:
    - object_key: 文件的对象键
    - expires_in: (可选) URL有效期（秒）
    
    返回:
    - 文件URL
    """
    object_key = request.query_params.get('object_key')
    if not object_key:
        return Response({
            'success': False,
            'message': '未提供文件标识'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 检查权限（这里应添加更多权限检查逻辑）
    
    # 获取过期时间
    try:
        expires_in = int(request.query_params.get('expires_in', 3600))
    except ValueError:
        expires_in = 3600
    
    file_url = file_service.get_file_url(object_key, expires_in=expires_in)
    
    return Response({
        'success': True,
        'data': {
            'file_url': file_url,
            'object_key': object_key,
            'expires_in': expires_in
        }
    })
